<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class Application extends Model
{
    // 表名
    protected $name = 'application';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';

    protected $type = [
        'createtime' => 'datetime:Y-m-d H:i:s'
    ];
    // 追加属性
    protected $append = [
    ];

    /**
     * @var null|static 实例对象
     */
    protected static $instance = null;

    /**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) self::$instance = new self($options);

        return self::$instance;
    }

    /**
     * 参与活动
     * @param array $params
     * @return int
     * @throws
     */
    public function add(array $params): int
    {
        Db::startTrans();
        try {
            $result = $this->allowField(true)->save($params);
            if ($result) {
                Db::commit();
                return $this->id;
            }
            throw new Exception('参与活动失败');
        } catch (Exception $exception) {
            Db::rollback();
            throw new Exception($exception->getMessage());
        }
    }

    public function userHasOne()
    {
        return $this->hasOne(User::class, 'id', 'user_id')
            ->field('id, nickname, avatar')
            ->bind('nickname,avatar');
    }
}